<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="chnageKeyword"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeNode"
          node-key="id"
          :data="treeData"
          :props="defaultProps"
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push({name:'employeeDetails'})">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportBtn">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.departmentName.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentId" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column prop="address" label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button
                size="mini"
                type="text"
                @click="$router.push({
                  name: 'employeeDetails',
                  params: {
                    id: row.id
                  }
                })"
              >查看</el-button>
              <el-button size="mini" type="text" @click="getAllRoleList(row.id)">角色</el-button>
              <!-- <el-button size="mini" type="text" @click="delBtn(row.id)">删除</el-button> -->
              <el-popconfirm title="确定要删除吗?" style="margin-left: 10px;" @confirm="delBtn(row.id)">
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="padding: 10px;">
          <el-pagination
            layout="total, prev, pager, next"
            :total="queryParams.total"
            :page-size="queryParams.pageSize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 员工数据导入弹层 -->
    <exportEmployee :show-excel-dialog.sync="showExcelDialog" @uploadData="getEmployeeList" />
    <!-- 点击角色弹出层 -->
    <el-dialog title="选择角色" :visible.sync="roleDialogVisible">
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in allRoleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isRoleListBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentAPI } from '@/api/department'
import {
  getAllRoleListAPI,
  getEmployeeDetailsAPI,
  putRoleListAPI
} from '@/api/employee'
import { transListToTreeData } from '@/utils/index'
import {
  getEmployeeListAPI,
  exportEmployeeAPI,
  delEmployeeAPI
} from '@/api/employee'
// 下载文件处理
import FileSaver from 'file-saver'
// 员工数据导入弹层
import exportEmployee from './components/exportEmployee.vue'

export default {
  name: 'Employee',
  components: {
    exportEmployee
  },
  data() {
    return {
      // 全部tree数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 请求表单数据的时候要携带给后端的参数
      queryParams: {
        departmentId: null,
        pageSize: 10,
        page: 1,
        keyword: '',
        total: 0
      },
      // 表单数据
      tableData: [],
      // 是否显示导入员工数据弹层
      showExcelDialog: false,
      // 角色列表弹出层能
      roleDialogVisible: false,
      // 渲染的数据
      allRoleList: [],
      // 点击当前的分配角色的id
      allRoleListId: '',
      // 选中的角色列表数据
      checkList: []
    }
  },
  created() {
    // 获取tree的数据
    this.getDepartment()
  },
  methods: {
    // 获取数组要渲染的数据
    async getDepartment() {
      // transListToTreeData 此方法是封装好的处理tree数据的方法(递归处理数据)
      this.treeData = transListToTreeData(await getDepartmentAPI(), 0)
      // 默认选中第一个跟节点
      this.queryParams.departmentId = this.treeData[0].id
      // 等待页面更新完之后再让根节点显示高亮效果
      this.$nextTick(() => {
        this.$refs.treeNode.setCurrentKey(this.queryParams.departmentId)
      })
      // 初始化员工数据
      this.getEmployeeList()
    },
    // 选中的节点发生变换时执行此回调
    selectNode(node) {
      this.queryParams.departmentId = node.id
      // 筛选员工数据
      this.getEmployeeList(this.queryParams)
      // 节点发生变换时，先发页面初始化为1，在调用回去数据的接口
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 获取员工数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeListAPI(this.queryParams)
      // 赋值
      this.tableData = rows
      // 总数量
      this.queryParams.total = total
    },
    // 当页码发生变化时出发
    changePage(page) {
      // 给页码重新赋值
      this.queryParams.page = page
      this.getEmployeeList()
    },
    // 搜索框发生变化时执行
    chnageKeyword() {
      this.queryParams.page = 1
      // 输入的数据每次发生变化都把上一次的定时器先清除，在重新发送数据请求(防抖效果)
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getEmployeeList()
      }, 500)
    },
    // 导出员工信息
    async exportBtn() {
      console.log(12123123)
      const res = await exportEmployeeAPI()
      // FileSaver(要转化的数据, '转化为什么格式')
      FileSaver.saveAs(res, '员工信息表.xlsx')
      this.$message.success('员工信息表下载完毕')
    },
    // 删除员工数据
    async delBtn(id) {
      await delEmployeeAPI(id)
      if (this.tableData.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      // 提示
      this.$message.success('删除成功')
      // 重新获取员工数据
      this.getEmployeeList()
    },
    // 获取已启用的角色列表
    async getAllRoleList(id) {
      // 获取所有角色
      this.allRoleList = await getAllRoleListAPI()
      // 获取点击当前的角色所占有的角色列表
      const { roleIds } = await getEmployeeDetailsAPI(id)
      // 给全局的 点击当前角色id赋值
      this.allRoleListId = id
      // 给当前有的角色赋值
      this.checkList = roleIds
      // 最后才弹出层
      this.roleDialogVisible = true
    },
    // 确认分配橘角色
    async isRoleListBtn() {
      await putRoleListAPI({
        id: this.allRoleListId,
        roleIds: this.checkList
      })
      this.$message.success('分配角色成功')
      this.roleDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
